package com.op.parcel.manage.config.security.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.op.parcel.manage.modules.sys.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.IOException;

/**
 * @author xuan🐽
 */
@Slf4j
public class SecurityUtil {

	@Autowired
	RedisTemplate<String, String> redisTemplate;

	@Autowired
	ObjectMapper objectMapper;

	/**
	 * 获取当前登录用户名
	 *
	 * @return
	 */
	public static String getUsername() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return "";
		}
		UserDetails user = (UserDetails) authentication.getPrincipal();
		return user.getUsername();
	}


	/**
	 * 获取当前登录用户名
	 * @return
	 * @throws IOException
	 */
	public String getUID() throws IOException {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return "";
		}
		UserDetails user = (UserDetails) authentication.getPrincipal();
		String userString = redisTemplate.opsForValue().get("user::" + user.getUsername());
		UserVO userVO = objectMapper.readValue(userString, UserVO.class);
		return userVO.getId();
	}

}
